<template>
    <Teleport to="#after-navigation" v-if="targetExists">
        <GradeManager />
    </Teleport>

    <div v-loading="loading">
        <h2 v-if="!roleStore.isStudent">{{ $t('grade.report.grader.index.tit') }}</h2>
        <div class="grade-navigation" v-if="courseId && !roleStore.isStudent">
            <MoodleTabs :list="tabsList" active="1" v-if="roleStore.isStudent" />
            <MoodleTabs :list="tabsList1" active="1" v-else />
        </div>
        <h3>{{ $t('grade.report.grader.index.search_res') }}2/2</h3>
        <QuickFilter @filter-change="handleFilterChange" />
        <div class="title-wrap">
             <h6 class="course-name">
                <el-icon size="16" color="#000"><Folder /></el-icon>
                {{ courseInfo?.name }}
            </h6>
            <el-button color="#F06423" @click="downloadHandle">{{ $t('mod.quiz.report.btn_text_1') }}</el-button>
        </div>
        <el-table v-if="userGradeList" :data="userGradeList.tableData" stripe border style="width: 100%" :default-sort="{ prop: 'student_name', order: 'ascending' }">
            <el-table-column :fixed="ind === 0" v-for="(col, ind) in userGradeList.columns" :key="col.prop" min-width="120">
                <template #default="{ row }">
                    <span v-if="col.prop === 'student_name'">{{ row[col.prop] === 'grade.report.grader.index.table_label_1' ? $t(row[col.prop]) : row[col.prop] }}</span>
                    <span class="grade-value" v-else>
                        {{ row[col.prop].grade }}
                        <!-- @click="goPage(`/console/course/unit/quiz/review/${col.record_id}`)" 这里需要一个作答记录的id -->
                        <el-icon size="16" color="#000" v-if="row[col.prop].grade != 0 && row.student_name !== 'grade.report.grader.index.table_label_1' && col.type === 'quiz'"><ZoomIn /></el-icon>
                    </span>
                </template>
                <template #header>
                    <div @click="goResourcePage(col)" class="item-name" :class="{ 'is-type': col.prop.type !== 'student_name' }" :title="col.label">
                        <el-icon size="16" color="#F06423" v-if="col.type === 'quiz'"><DocumentChecked /></el-icon>
                        <el-icon size="16" color="#06AAFF" v-else-if="col.type === 'video'"><VideoPlay /></el-icon>
                        <el-icon size="16" color="#616161" v-else-if="col.type === 'reflection'"><Memo /></el-icon>
                        <el-icon size="16" color="#999999" v-else-if="col.type === 'total'"><DataAnalysis /></el-icon>
                        <span class="over-1">{{ col.label === 'grade.report.grader.index.table_label_2' ? $t(col.label) : col.label }}</span>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute } from 'vue-router'

import MoodleTabs from '@/components/MoodleTabs.vue'
import GradeManager from '@/components/GradeManager.vue'
import QuickFilter from '@/components/QuickFilter.vue'

import CourseService from '@/api/course'
import type { CourseItem } from '@/types/course'

import { useRoleStore } from '@/stores/role'
import { goPage, downloadCSV } from '@/utils/global'

interface FilterParams {
    additional_first_initial: string
    additional_last_initial: string
}

const route = useRoute()
const roleStore = useRoleStore()
const courseId = computed(() => Number(route.params.courseId))
const loading = ref(false)
const targetExists = ref(false)

const tabsList = ref([
    {
        value: '1',
        link: `/console/course/${courseId.value}/grade`,
        text: 'grade.report.grader.index.tabs_1', // 綜覽報告
    },
    {
        value: '2',
        link: `/console/course/${courseId.value}/grade/user`,
        text: 'grade.report.grader.index.tabs_2', // 用戶報告
    },
])
const tabsList1 = ref([
    {
        value: '1',
        link: `/console/course/${courseId.value}/grade/rater`,
        text: 'grade.report.grader.index.tabs_3', // 評分者報告
    },
    {
        value: '3',
        link: `/console/course/${courseId.value}/grade/user`,
        text: 'grade.report.grader.index.tabs_2', // 用戶報告
    },
])

// 姓氏和名字 篩選
const filters = ref<FilterParams>({
    additional_first_initial: '',
    additional_last_initial: '',
})
const handleFilterChange = (newFilters: any) => {
    filters.value = {
        additional_first_initial: newFilters.firstName == 'all' ? '' : newFilters.firstName,
        additional_last_initial: newFilters.lastName == 'all' ? '' : newFilters.lastName
    }
    getGradeList()
}

// 下载
import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()
const exportLoading = ref(false);
const downloadHandle = () => {
    const params = {
        course_id: courseId.value,
        additional_first_initial: filters.value.additional_first_initial,
        additional_last_initial: filters.value.additional_last_initial,
        export: 'csv',
    }
    exportLoading.value = true
    CourseService.exportInfoAllStudyDetail(params)
        .then(res => {
            downloadCSV(res, t('grade.report.grader.index.tit', ''))
        })
        .finally(() => {
            exportLoading.value = false
        })
}

// 成員列表
const userGradeList = ref<any>()
const goResourcePage = (grade: any) => {
    switch (grade.type) {
        case 'quiz':
            goPage(`/console/course/${courseId.value}/unit/${grade.unit_id}/quiz/${grade.id}`)
            break
        case 'video':
            goPage(`/console/course/${courseId.value}/unit/${grade.unit_id}/videoTime/${grade.id}`)
            break
        case 'reflection':
            goPage(`/console/course/${courseId.value}/unit/${grade.unit_id}/assign/${grade.id}`)
            break
    }
}
function getGradeList() {
    loading.value = true
    CourseService.gradesToTeacher(courseId.value, filters.value)
        .then(res => {
            userGradeList.value = res
        })
        .finally(() => {
            loading.value = false
        })
}

// 課程資訊
const courseInfo = ref<CourseItem>()
function getCourseInfo() {
    CourseService.getById(courseId.value).then(res => {
        courseInfo.value = res
    })
}

onMounted(() => {
    getGradeList()
    getCourseInfo()
    targetExists.value = !!document.querySelector('#before-navigation')
})
</script>

<style lang="less" scoped>
.title-wrap{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-content: center;
    margin-bottom: 15px;
}
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

h3 {
    margin-bottom: 18px;
    font-size: 26px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.grade-navigation {
    margin-bottom: 30px;
}

.course-name {
    font-weight: bold;
    font-size: 14px;
    color: #000;
    display: flex;
    align-items: center;
    gap: 4px;
}

.item-name {
    color: #000;

    display: flex;
    align-items: center;
    gap: 8px;

    &.is-type {
        cursor: pointer;
    }

    &:hover {
        color: #f06423;
    }
}

.grade-value {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .el-icon {
        cursor: pointer;
    }
}
</style>
